<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyJstPurchaseinOrderEmbroideryCountTable;
use App\Http\Models\Mysql\SsyJstPurchaseinOrderTable;
use App\Http\Models\Mysql\SsyPricingExamineTable;
use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\VerifyPriceTable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class returnStatistic extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:returnStatistic';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '回货统计表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $lastMonth = date('Y-m', strtotime("- 1 month"));
        $startDay = date('Y-m-01 00:00:00', strtotime('- 1 month'));
        $endDay = date('Y-m-t 23:59:59', strtotime('- 1 month'));
        $exist = (new SsyJstPurchaseinOrderEmbroideryCountTable())->where('r_years', $lastMonth)->first();
        if(!empty($exist)){
            die("$lastMonth 的回货统计表数据已经生成!");
        }
        $orderList = (new SsyJstPurchaseinOrderTable())->where('wh_id', 3)->whereNotNull('po_id')->whereBetween('ke_date', [$startDay, $endDay])
            ->groupBy(["processing_code","po_id","supplier_id"])->get(["processing_code","po_id","supplier_id"])->toArray();
        DB::beginTransaction();
        try{
            $total = count($orderList);
            $num = 1;
            foreach($orderList as $item){
                echo "正在处理, 第[$total, $num]条: {$item['processing_code']} {$item['po_id']}\n";
                $num++;
                //加工单
                $processingObj = (new SsyProcessingListTable())->where('processing_code', $item['processing_code'])->first();
                $processingObj = !empty($processingObj) ? $processingObj->toArray() : [];
                $factoryObj = (new SsyProcessingFactoryNameTable())->where('supplier_id', $item['supplier_id'])->first(['factory_name']);
                $detail = (new SsyJstPurchaseinOrderTable())->where('po_id', $item['po_id'])->whereBetween('ke_date', [$startDay, $endDay])->get(['id', 'qty'])->toArray();
                $totalNum = array_sum(array_column($detail, 'qty'));
                //加工单核价审核
                $examineObj = (new SsyPricingExamineTable())->where('processing_code', $item['processing_code'])->first();
                $examineObj = !empty($examineObj) ? $examineObj->toArray() : [];
                //大货核价
                $bigVerifyPriceObj = (new VerifyPriceTable())->where('number', $processingObj['verify_price_number'] ?? "")->first();
                $bigVerifyPriceObj = !empty($bigVerifyPriceObj) ? $bigVerifyPriceObj->toArray() : [];
                //实付核价
                $payVerifyPriceObj = (new VerifyPriceTable())->where('number', $examineObj['pay_pricing_number'] ?? "")->first();
                $payVerifyPriceObj = !empty($payVerifyPriceObj) ? $payVerifyPriceObj->toArray() : [];
                //绣花厂id
                $embroideryFactoryObj = ($processingObj['embroidery_factory'] ?? "") ? (new SsyProcessingFactoryNameTable())->where(function ($query) use ($processingObj){
                    $query->where('factory_name_jiancheng', $processingObj['embroidery_factory'])
                        ->orwhere('factory_name', $processingObj['embroidery_factory']);
                })->first(['supplier_id']) : [];
                $embroideryFactoryObj = !empty($embroideryFactoryObj) ? $embroideryFactoryObj->toArray() : [];
                $data = [
                    'processing_code' => $item['processing_code'],
                    'so_id' => $item['processing_code'],
                    'po_id' => $item['po_id'],
                    'supplier_id' => $item['supplier_id'],
                    'factory_name' => $factoryObj->factory_name ?? "",
                    'order_processor' => $processingObj['order_processor'] ?? "",
                    'type_no' => $processingObj['type_no'] ?? "",
                    'type_name' => $processingObj['type_name'] ?? "",
                    'totalnum' => $totalNum,
                    'status' => $examineObj['status'] ?? 0,
                    'contract_machining_price' => $bigVerifyPriceObj['f63'] ?? 0,//大货绣花价格
                    'pay_machining_price' => $payVerifyPriceObj['f63'] ?? 0,//实付绣花价格
                    'total_cost_amount' => round(($payVerifyPriceObj['f63'] ?? 0) * $totalNum, 2),//绣花金额
                    'contract_price' => $examineObj['process_pricing_price'] ?? 0,//大货成衣成本加价总价
                    'pay_price' => $examineObj['pay_process_price'] ?? 0,//实付成衣成本加价总价
                    'cost_amount' => round(($examineObj['pay_process_price'] ?? 0) * $totalNum, 2),//成衣金额
                    'ids' => serialize(array_column($detail, 'id')),
                    'embroidery_factory' => $processingObj['embroidery_factory'] ?? "",
                    'embroidery_factory_id' => $embroideryFactoryObj['supplier_id'] ?? "",
                    'r_years' => $lastMonth,
                    'brand_code' => $processingObj['brand_code'] ?? "",
                    'createtime' => date('Y-m-d H:i:s')
                ];
                $res = (new SsyJstPurchaseinOrderEmbroideryCountTable())->createData($data);
                if($res['code'] !== 0){
                    DB::rollBack();
                    break;
                }
            }
            DB::commit();
        }catch (\Exception $e){
            info("回货统计表", [$e->getMessage()]);
            DB::rollBack();
        }
    }
}
